package com.sst.common.Test.DataImport;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class HeroBatchHandler {

    public static int batchSave(List<Hero> heroList, String threadName) throws Exception {
        String sql = "INSERT INTO hero(id,hero_name,age,weapon,city) VALUES(?,?,?,?,?)";
        // 创建JDBC对象
        PreparedStatement pst = null;
        // 连接对象
        Connection conn = null;

        Hero hero;
        int[] count = new int[0];

        try {
            conn = DataSourceUtils.getConnection();
            pst = conn.prepareStatement(sql);
            // 关闭自动提交，非常耗时
            conn.setAutoCommit(false);
            long start = System.currentTimeMillis();
            if (null != heroList && heroList.size() > 0) {
                for (int i = 0; i < heroList.size(); i++) {
                    hero = heroList.get(i);
                    // sql语句
                    pst.setString(1, hero.getId());
                    pst.setString(2, hero.getHeroName());
                    pst.setInt(3, hero.getAge());
                    pst.setString(4, hero.getWeapon());
                    pst.setString(5, hero.getCity());
                    // 加入批处理
                    pst.addBatch();
                }
                // 提交数据
                count = pst.executeBatch();
                // 清空容器
                pst.clearBatch();
                // 手动提交
                conn.commit();
//				int size = userList.size();
                System.out.println(count.length);
                System.out.println(" threadName为" + threadName + ", sync data to db, it  has spent "
                        + (System.currentTimeMillis() - start) + "  ms");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 释放资源
            DataSourceUtils.close(conn, pst);
        }
        // 获取到数据更新的行数
        return count.length;
    }
}
